package com.lyj.units;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取spring context 中的bean
 */
public class SpringHelp implements ApplicationContextAware {

    private static ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 获取 ApplicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        if (null == context) {
            throw new RuntimeException();
        }
        return context;
    }

    /**
     * 通过bean名称 获取 ApplicationContext 的bean 实例
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过类 类型获取bean实例
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T>T getBean(Class<T> tClass) {
        return getApplicationContext().getBean(tClass);
    }

    /**
     * 通过 bean名称 及 类型 获取bean实例
     *
     * @param name
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T>T getBean(String name , Class<T> tClass) {
        return getApplicationContext().getBean(name,tClass);
    }

}
